package com.sophialex.health.record.common;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.events.ShellListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;


import com.sophialex.health.system.frame.resource.RcpResourceManager;
import com.sophialex.health.system.frame.widgets.treeCombo.TreeCheckUtil;
import com.sophialex.health.system.frame.widgets.treeCombo.TreeComboInit;
/**
 * 居委会选择控件
 * <p>Title:Health</p>
 * <p>GeographyTreeCombo</p>
 * 
 * Alex Apr 25, 2011 10:20:25 PM create
 * @author <a href='wanghao924@126.com'>Alex</a>
 * QQ: 873987060;
 * @version 1.0
 */
public class GeographyTreeCombo extends Composite {

	private Text text;
	private Button button, btnOK;
	private Point point;
	private ComboShell popup;// = new ComboShell(this.getShell());
	private Tree tree;// = popup.getTree();
	private TreeComboInit init;

	private TreeItem selectedItem;

	public Tree getTree() {
		return tree;
	}

	public void setTree(Tree tree) {
		this.tree = tree;
	}

	public Point getPoint() {
		return point;
	}

	public void setPoint(Point point) {
		this.point = point;
	}

	public String getText() {
		return text.getText();
	}

	public void setText(String text) {
		this.text.setText(text);
	}

	public void setSelection(int index) {
		if (tree != null && index < tree.getItemCount() && index >= 0) {
			tree.setSelection(tree.getItem(0));
			text.setText(tree.getItem(0).getText());
			selectedItem = tree.getItem(0);
		}
	}

	/**
	 * 树节点对象的data值
	 * 
	 * @param value
	 */
	public void setSelection(Object data) {
		if (tree != null) {
			for (TreeItem it : tree.getItems()) {
				setSelection(it, data);
			}
		}
	}

	public void setSelection(TreeItem item, Object data) {
		if (item.getData().equals(data)) {
			tree.setSelection(item);
			text.setText(item.getText());
			selectedItem = item;
		} else {
			if (item.getItemCount() > 0) {
				for (TreeItem it : item.getItems()) {
					setSelection(it, data);
				}
			}
		}
	}

	/**
	 * Create the composite
	 * 
	 * @param parent
	 * @param style
	 */
	public GeographyTreeCombo(Composite parent, TreeComboInit init) {
		super(parent, SWT.SCROLL_LINE | SWT.BORDER);
		this.init = init;
		setLayout(new FormLayout());
		popup = new ComboShell(this.getShell());
		tree = popup.getTree();
		text = new Text(this, SWT.NONE);
		text.setSize(191, 374);
		text.setEditable(false);
		text.setBackground(RcpResourceManager.getColor(255, 255, 255));
		final FormData fd_text = new FormData();
		fd_text.right = new FormAttachment(100, -16);
		fd_text.bottom = new FormAttachment(100);
		fd_text.top = new FormAttachment(0, 0);
		fd_text.left = new FormAttachment(0, 0);
		text.setLayoutData(fd_text);
		button = new Button(this, SWT.ARROW | SWT.DOWN);
		final FormData fd_button = new FormData();
		fd_button.bottom = new FormAttachment(text, 0, SWT.BOTTOM);
		fd_button.top = new FormAttachment(0);
		fd_button.left = new FormAttachment(text);
		fd_button.right = new FormAttachment(100);
		button.setLayoutData(fd_button);
		popup.setVisible(false);
		addListenter();
		addDisposeListener(new DisposeListener() {
			public void widgetDisposed(final DisposeEvent e) {
				popup.dispose();
				popup = null;
			}
		});
	}

	public GeographyTreeCombo(Composite parent, TreeComboInit init, int treeStyle) {
		super(parent, SWT.SCROLL_LINE | SWT.BORDER);
		this.init = init;
		setLayout(new FormLayout());
		popup = new ComboShell(this.getShell(), treeStyle);
		tree = popup.getTree();
		text = new Text(this, SWT.NONE);
		text.setEditable(false);
		text.setBackground(RcpResourceManager.getColor(255, 255, 255));
		final FormData fd_text = new FormData();
		fd_text.right = new FormAttachment(100, -16);
		fd_text.bottom = new FormAttachment(100);
		fd_text.top = new FormAttachment(0, 0);
		fd_text.left = new FormAttachment(0, 0);
		text.setLayoutData(fd_text);
		button = new Button(this, SWT.ARROW | SWT.DOWN);
		final FormData fd_button = new FormData();
		fd_button.bottom = new FormAttachment(text, 0, SWT.BOTTOM);
		fd_button.top = new FormAttachment(0);
		fd_button.left = new FormAttachment(text);
		fd_button.right = new FormAttachment(100);
		button.setLayoutData(fd_button);
		popup.setVisible(false);
		addListenter();
		addDisposeListener(new DisposeListener() {
			public void widgetDisposed(final DisposeEvent e) {
				popup.dispose();
				popup = null;
			}
		});
	}

	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}

	public void addModifyListener(ModifyListener modifyListener) {
		text.addModifyListener(modifyListener);
	}

	public void addListenter() {

		button.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				// popup.setParent(button.getShell());
				dropDown();
			}
		});

		btnOK.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				doWidgetSelected();
				popup.setVisible(false);
			}
		});
		tree.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {

				TreeItem item = (TreeItem) e.item;
				// if (!tree.getItem(0).equals(item)) {
				selectedItem = item;
				text.setText(item.getText().trim());
				popup.setVisible(false);
				// }
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				popup.setVisible(false);
				TreeCheckUtil.removeAllChecked(tree);
			}

		});

		popup.addShellListener(new ShellListener() {
			public void shellActivated(ShellEvent e) {
				// TODO Auto-generated method stub

			}

			public void shellClosed(ShellEvent e) {
				// TODO Auto-generated method stub

			}

			// 没有被激活事件
			public void shellDeactivated(ShellEvent e) {
				// TODO Auto-generated method stub
				boolean flag = button.isFocusControl();
				if (!flag)
					popup.setVisible(false);
			}

			public void shellDeiconified(ShellEvent e) {
				// TODO Auto-generated method stub

			}

			public void shellIconified(ShellEvent e) {
				// TODO Auto-generated method stub

			}
		});
	}

	protected void doWidgetSelected() {
		Object objdata = new Object();
		String stext = "";
		objdata = tree.getSelection()[0].getData();
		stext = tree.getSelection()[0].getText().trim();

		text.setText(stext);
		text.setData(objdata);

	}

	/**
	 * 深度遍历树
	 * 
	 * @param treeItem
	 *            根结点item
	 * @return
	 */

	private void generateKsKhOnlyLeaf(TreeItem item, StringBuilder nameX,
			StringBuilder codeX) {
		TreeItem itt = item;
		if (itt != null && itt.getChecked() && itt.getItemCount() == 0) {
			nameX.append(itt.getText()).append(",");
			codeX.append("'").append(itt.getData().toString()).append("',");
			return;
		}
		int i = 0;
		while (itt != null && TreeCheckUtil.hasCheckedItem(itt)
				&& itt.getItemCount() > 0 && i < itt.getItemCount()) {
			generateKsKhOnlyLeaf(itt.getItem(i), nameX, codeX);
			i++;
		}

	}

	/**
	 * 深度遍历树,递归产生名称以及相应的编号,编号带单引号
	 * 
	 * @param treeItem
	 *            根结点item
	 * @return
	 */

	private void generateKsKh(TreeItem item, StringBuilder nameX,
			StringBuilder codeX) {
		TreeItem itt = item;

		if (itt != null && itt.getItemCount() > 0) {
			int j = 0;
			while (j < itt.getItemCount() && itt.getItem(0) != null
					&& itt.getItem(0).getItemCount() > 0) {
				generateKsKh(itt.getItem(j), nameX, codeX);
				j++;
			}
			if (TreeCheckUtil.hasAllCheckedItem(itt)) {
				itt.setChecked(true);
				if (itt.getParentItem() == null) {
					nameX.append(itt.getText()).append(",");
					codeX.append("'").append(itt.getData().toString()).append(
							"',");
					return;
				}
			} else {
				itt.setChecked(false);
				if (TreeCheckUtil.hasCheckedItem(itt)) {

					int i = 0;
					while (i < itt.getItemCount()) {
						if (itt.getItem(i) != null
								&& itt.getItem(i).getChecked()) {
							nameX.append(itt.getItem(i).getText()).append(",");
							codeX.append("'").append(
									itt.getItem(i).getData().toString())
									.append("',");
						}
						i++;
					}
				}
			}
		}

	}

	public String getSqlText() {
		return (String) text.getData("Sql");
	}

	public Object getTreeItemData() {
		if (selectedItem != null) {
			return selectedItem.getData();
		} else
			return null;
	}

	public void dropDown() {
		if (!popup.isVisible()) {
			try {
				Rectangle r = text.getBounds();
				int y1 = r.y + r.height;
				Display display = Display.getCurrent();
				Rectangle parentRect = display.map(getParent(), null,
						getBounds());
				Point comboSize = getSize();
				Rectangle displayRect = getMonitor().getClientArea();
				int width = Math.max(comboSize.x, 10 + 2);
				int height = 5 + 2;
				int x = parentRect.x;
				int y = parentRect.y + comboSize.y;
				if (y + height > displayRect.y + displayRect.height)
					y = parentRect.y - height;
				if (x + width > displayRect.x + displayRect.width)
					x = displayRect.x + displayRect.width - 10;
				popup.setBounds(x, y, width + 100, 220);
				popup.setVisible(true);
				popup.open();
				popup.layout();
				while (popup != null && !popup.isDisposed()) {
					if (!display.readAndDispatch())
						display.sleep();
				}
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		} else {
			popup.setVisible(false);
		}

	}

	@Override
	public String getData() {
		return text.getData().toString();
	}

	public void setData(String sql) {
		text.setData(sql);
	}

	// 弹出的shell
	class ComboShell extends Shell {
		private Tree tree;
		private int treeStyle = SWT.NONE | SWT.CHECK | SWT.MULTI;

		/**
		 * Launch the application
		 * 
		 * @param args
		 */

		public Tree getTree() {
			return tree;
		}

		public void setTree(Tree tree) {
			this.tree = tree;
		}

		/**
		 * Create the shell
		 * 
		 * @param display
		 * @param style
		 */
		public ComboShell() {
			super(SWT.ON_TOP | SWT.TOOL);// 无提示栏
			createContents();
			setLayout(new FillLayout());
		}

		/**
		 * 可以设置Tree样式的combo
		 * 
		 * @param shell
		 * @param treeStyle2
		 */
		public ComboShell(Shell shell, int treeStyle2) {
			super(shell, SWT.ON_TOP | SWT.TOOL);// 无提示栏
			this.treeStyle = treeStyle2;
			createContents();
			setLayout(new FillLayout());
		}

		/**
		 * Create the shell
		 * 
		 * @param display
		 * @param style
		 */
		public ComboShell(Shell parent) {
			super(parent, SWT.ON_TOP | SWT.TOOL);// 无提示栏
			createContents();
			setLayout(new FillLayout());
		}

		/**
		 * Create contents of the window
		 */
		protected void createContents() {
			setBackground(RcpResourceManager.getColor(240, 240, 245));
			final Composite container = new Composite(this, SWT.NONE);
			container.setBackground(RcpResourceManager.getColor(240, 240, 245));
			container.setLayout(new GridLayout());
			tree = new Tree(container, this.treeStyle);
			TreeCheckUtil.addCheckItemListener(tree);
			tree.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
			btnOK = new Button(container, SWT.NONE);
			final GridData gd_btnOK = new GridData(SWT.CENTER, SWT.CENTER,
					false, false);
			gd_btnOK.widthHint = 57;
			gd_btnOK.heightHint = 1;
			btnOK.setLayoutData(gd_btnOK);
			btnOK.setText("确定");
			init.initTree(tree);
			btnOK.setVisible(false);

		}

		@Override
		protected void checkSubclass() {
			// Disable the check that prevents subclassing of SWT components
		}
	}
}